package hn.cch.druid.query;



import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * where SQL语句
 *
 * @author CCH
 * @version 2018.08.31
 */
public class Where {

    //连接符
    private Joiner joiner;
    //条件
    private List<Condition> conditions;


    public Where(Joiner joiner, List<Condition> conditions) {
        this.joiner = joiner;
        this.conditions = conditions;
    }

    public Joiner getJoiner() {
        return joiner;
    }

    public void setJoiner(Joiner joiner) {
        this.joiner = joiner;
    }

    public List<Condition> getConditions() {
        return conditions;
    }

    public void setConditions(List<Condition> conditions) {
        this.conditions = conditions;
    }

    public Where add(Operator operator, String key, Object value){
        conditions.add(new Condition(operator, key, value));
        return this;
    }

    public String toString(){

        if(conditions == null||!conditions.iterator().hasNext()){
            return new String("");
        }

        List<String> strs = new ArrayList<>();

        Iterator<Condition> iterator = conditions.iterator();

        int index = 0;

        while (iterator.hasNext()){
            Condition condition = iterator.next();
            if (condition.getKey() == null){
                continue;
            }
            String str = condition.getKey() + " " + condition.getOperator().getName() + "" + (org.springframework.util.StringUtils.replace(condition.getKey(), ".", "_") + index);

            strs.add(str);

            index++;
        }

        String string = org.apache.commons.lang3.StringUtils.join(strs, " " + joiner.name() + "");


        return org.apache.commons.lang3.StringUtils.isEmpty(string)?"":" WHERE " + string;



    }


}
